package com.java.multipledatasource.thread;

/**
 * @author hu
 * @version 1.0
 * @date 2021/1/16 0016 下午 7:42
 * @description 两个线程交替打印
 */
public class Thread3 {

    private static volatile  int count = 0;

    static   Thread t1 = null;

    static   Thread t2 = null;
    static  volatile  boolean flag = true;
    static final Object lock = new Object();

    public static void main(String[] args) {

        new Thread(() -> {
            while (count < 10) {
                synchronized (lock) {
                    if (flag) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }  else {
                        count++;
                        System.out.println(Thread.currentThread().getName()  + "    " + count);
                        flag = true;
                        lock.notify();
                    }
                }
            }
        }, "t1").start();

        new Thread(() -> {
            while (count < 10) {
                synchronized (lock) {
                    if (!flag) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }  else {
                        count++;
                        System.out.println(Thread.currentThread().getName()  + "    " + count);
                        flag = false;
                        lock.notify();
                    }
                }
            }
        }, "t2").start();


    }
}
